package com.sinosoft.brokerchannel.base.utile;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinosoft.brokerchannel.base.bins.Template;
import com.sinosoft.brokerchannel.base.filters.JacksonFilter;

/**
 * Jackson序列化类
 */
public class JacksonSerializer {
    /**
     * Jackson中操作Java对象与json转换的类
     */
    private ObjectMapper mapper = null;
    /**
     * Jackson过滤器
     */
    private JacksonFilter jacksonFilter = null;

    public JacksonSerializer(ObjectMapper mapper, JacksonFilter jacksonFilter) {
        this.mapper = mapper;
        this.jacksonFilter = jacksonFilter;
    }

    /**
     * 选择、添加某个类的属性
     *
     * @param clazz   target type 操作的类
     * @param include include fields 包含的属性
     * @param filter  filter fields 要过滤掉的属性
     */
    private void filter(Class<?> clazz, String[] include, String[] filter) {
        if (clazz == null) {
            return;
        }
        if (include != null && include.length > 0) {
            jacksonFilter.include(clazz, include);
        }
        if (filter != null && filter.length > 0) {
            jacksonFilter.filter(clazz, filter);
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    /**
     * @param object 任何Java对象
     * @return 序列化后的字符串
     * @throws JsonProcessingException
     * @方法描述:序列化任何Java对象
     * @参数说明：
     */
    public String writeValueAsString(Object object) throws JsonProcessingException {
        mapper.setFilterProvider(jacksonFilter);
        return mapper.writeValueAsString(object);
    }

    /**
     * @param t {@link Template} 自定义的模板
     * @方法描述:按自定义模板过滤字段
     * @参数说明：
     */
    public void filter(Template t) {
        this.filter(t.getType(), t.getInclude(), t.getFilter());
    }
}
